using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Data.Linq.Mapping;

namespace ClubWebsite
{
    public partial class EmailUserPassword : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Enter QueryString parameters into the controls if they're provided
                if (Request.QueryString["Email"] != null)
                {
                    txtEmail.Text = HttpUtility.HtmlDecode(Request.QueryString["Email"].Trim());
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            // Go back a page
            Response.Redirect(Request.UrlReferrer.ToString());
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // Validation
            lblError.Visible = false;
            valEmail.Validate();
            if (!valEmail.IsValid)
            {
                return;
            }

            // Get the details of the user
            var userProperties = Functions.GetDatabaseDataContext()
                .Users
                .Where(u => u.Email.ToLower() == txtEmail.Text.Trim().ToLower())
                .Select(u => new { u.Email, u.Password })
                .Single();

            // Send an email to the user with their password
            try
            {
                WebsiteEmail.SendEmailWithPassword(userProperties.Email, userProperties.Password);
                pnlSendPassword.Visible = false;
                pnlPasswordSent.Visible = true;

            }
            catch (Exception ex)
            {
                // Log the issue and let the user know there is a problem sending the email
                Functions.WriteLogEntry("Exception", true, ex);
                lblError.Text = "Unable to send the email.<br /><br />Error: " + ex.Message;
                lblError.Visible = true;
                return;
            }
        }

        protected void valEmail_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Required
            if (txtEmail.Text.Trim().Length == 0)
            {
                valEmail.ErrorMessage = "An entry is required";
                args.IsValid = false;
                return;
            }

            // Max length
            int maxLength = typeof(User).GetProperties()
                .Where(p => p.Name.ToLower() == "email")
                .Select(p => Functions.GetColumnSize((ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).First()))
                .First();
            if (txtEmail.Text.Trim().Length > maxLength)
            {
                valEmail.ErrorMessage = String.Format("The entry cannot be more than {0} characters", maxLength);
                args.IsValid = false;
                return;
            }

            // Exists
            bool emailExists = Functions.GetDatabaseDataContext()
                .Users
                .Any(u => u.Email.ToLower() == txtEmail.Text.Trim().ToLower());
            if (!emailExists)
            {
                valEmail.Text = "This email address is not registered on this website.";
                args.IsValid = false;
                return;
            }
        }
    }
}